"""
Copyright © 2023 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-mini-calendar
"""
__version__ = '0.0.1'
__version_info__ = (0, 0, 1)
print('module utilities version:', __version__)


import time
import ntptime
from machine import RTC
from utils.wifihandler import WifiHandler


class Utilities(object):
	@staticmethod
	def import_config():
		try:
			Config = __import__('./config').Config
		except ImportError:
			from config import Config

		return Config

	@staticmethod
	def soft_reset():
		from sys import exit
		exit()

	@staticmethod
	def hard_reset():
		from machine import reset
		reset()

	@staticmethod
	def sync_time(retry=5) -> bool:
		if WifiHandler.is_sta_connected():
			TIMEZONE = Utilities.import_config().TIMEZONE

			print('syncing time...')

			for _ in range(retry):
				try:
					ntptime.settime()
					now = time.localtime() # (year, month, mday, hour, minute, second, weekday, yearday)
					RTC().datetime((now[0], now[1], now[2], now[6], now[3] + TIMEZONE, now[4], now[5], 0))
					now = time.localtime()
					print(f'- success: {now[0]}-{now[1]:02d}-{now[2]:02d} {now[3]:02d}:{now[4]:02d}:{now[5]:02d}')
					return True
				except OSError as ose:
					if str(ose) in ('[Errno 116] ETIMEDOUT', '-202'):
						pass
					else:
						print(ose)
				except Exception as e:
					print(e)

				time.sleep_ms(200)

			if time.time() < 60 * 60 * 2:
				# first time sync time failed, reset
				Utilities.hard_reset()
			else:
				print(f'- Cannot reach ntp host: {ntptime.host}, sync time failed')
				now = time.localtime()
				print(f'- RTC: {now[0]}-{now[1]:02d}-{now[2]:02d} {now[3]:02d}:{now[4]:02d}:{now[5]:02d}')
		else:
			print('- No wifi connected, sync time cancelled')

		return False


if __name__ == '__main__':
	print('connecting to internet...')
	if WifiHandler.STATION_CONNECTED == WifiHandler.set_sta_mode(timeout_sec=120):
		Utilities.sync_time(3)
	else:
		Utilities.hard_reset()
